var uploadValid = {
  "zip": "zip,rar,tar,gzip,gz,7z",
  "code": "php,js,css,htm,html",
  "audio": "mp3",
  "image": "jpg,jpeg,png,gif,bmp,webp",
  "file": "doc,docx,wps,xls,xlsx,csv,ppt,pptx,txt,md,jpg,jpeg,png,gif,bmp,mp3,MP4,mov,zip,rar,tar,gzip,gz,7z, WebM, Ogv,webp,svga",
  "xls": "xls,xlsx,csv",
  "video": "MP4, WebM, Ogv"
};
var uploadHelper = {

  //初始化数据
  /*
  initData:function(obj,list){
      var option = obj.data();
      var theme = option.theme;
      var box = option.box || 'upload-list'; //存放附件容器
      var name = option.name || 'upload';
      eval(themeCallfn[theme] + '(obj,list,name)');
  },
  */
  //将base64转换为文件  
  dataURLtoFile: function (dataurl, filename) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {type: mime});
  },
  //选择文件组的过滤方法
  filter: function (files, obj) {
    var arr = [];
    var exception = [];
    var option = obj.data();
    var type = option.type || 'image';
    var ext = option.ext || ''; //自定义扩展名
    var compress = option.compress == 0 ? 0 : 1; //是否压缩图片 默认压缩
    var allowExt = ext == '' ? uploadValid[type].split(',') : ext.split(','); //允许扩展名
    var fileNumber = files.length;
    for (var i in files) {
      if (files[i].constructor == File) {
        var file = files[i];
        var fileExtension = file.name.split('.').pop(); //后缀名
        if ($.inArray(fileExtension, allowExt) >= 0) {
          if (compress == 1) {
            if ($.inArray(fileExtension, ['jpg']) >= 0) {  //压缩图片
              lrz(file, {width: 1440, quality: 0.8}).then(function (rst) {
                var base2file = uploadHelper.dataURLtoFile(rst.base64, rst.origin.name);
                arr.push(base2file);
              });
            } else { //无需压缩文件
              arr.push(file);
            }
          } else {
            arr.push(file);
          }
        } else {
          exception.push('[' + file.name + ']类型不正确');
        }
      }
    }
    return exception.length > 0 ? {code: 0, data: exception} : {code: 1, fileNumber: fileNumber, data: arr};
  },
  //获取选择文件 obj为上传dom元素
  funGetFiles: function (e, obj) {
    var files = e.target.files || e.dataTransfer.files;
    var res = this.filter(files, obj);
    if (res.code == 0) {
      alert(res.data.join(','));
      return false;
    }
    this.funUploadFile(res.data, res.fileNumber, obj);
  },
  //上传文件
  funUploadFile: function (files, fileNumber, obj) {
    var timer = setInterval(function () {    //开启定时器
      if (files.length > 0 && files.length == fileNumber) {
        clearInterval(timer);    //清除定时器
        //这里应该判断总上传文件数量，超出停止执行
        var option = obj.data();
        var theme = option.theme;
        var type = option.type || 'image';
        var ext = option.ext || ''; //自定义扩展名
        var formData = new FormData();
        for (var i in files) formData.append("file[]", files[i]); //上传文件
        formData.append('type', type); //上传类型
        if (ext != '') formData.append('ext', ext); //上传后缀名
        if (option.hasOwnProperty('driver')) formData.append('driver', option.driver); //驱动
        if (option.hasOwnProperty('group')) formData.append('group_id', option.group); //分组id
        $.ajax({
          url: option.url || '/system/upload/file.html', /*接口域名地址*/
          type: 'post',
          data: formData,
          contentType: false,
          processData: false,
          xhr: function () {
            var xhr = $.ajaxSettings.xhr();
            console.info(xhr);
            if (xhr.upload) {
              xhr.upload.addEventListener("progress", uploadHelper.onprogress, false);
              return xhr;
            }
          },
          success: function (res) {
            obj.find("input[type='file']").val(''); //重置为空，防止重复文件无法上传
            if (res.code == 0) {
              alert(res.msg);
            } else {
              if (typeof option['callfn'] != 'undefined') {
                eval(option['callfn'] + '(res.data, obj)');
              } else {
                var Fun = option.themeFun || theme;
                eval('themeCallfn.' + Fun + '(res.data,obj)');
              }
            }
          }
        });
      }
    }, 300);
  },
  onprogress:function(evt){ //上传进度条
    console.info(evt);
    let loaded = evt.loaded;     //已经上传大小情况
    let tot = evt.total;      //附件总大小
    let per = Math.floor(100*loaded/tot);  //已经上传的百分比
    console.info(per,evt);
  }
};